#!/bin/sh
# $FreeBSD: ports/x11/gdm/files/gdm.in,v 1.20 2010/07/25 19:35:05 kwm Exp $
#    $MCom: ports-stable/x11/gdm/files/gdm.in,v 1.5 2010/07/21 13:50:46 kwm Exp $

# PROVIDE: gdm
# REQUIRE: LOGIN cleanvar moused syscons dbus
#
# Add the following to /etc/rc.conf to start GDM at boot time:
#
# gdm_enable="YES"
#

. /etc/rc.subr
. /usr/local/etc/gnome.subr

gdm_enable=${gdm_enable-${gnome_enable}}
gdm_preserve_base_pam_conf=${gdm_preserve_base_pam_conf-NO}
gdm_lang=${gdm_lang-${LANG}}

export PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin

setup_xorg() {
	/usr/local/share/pcbsd/xorg-gui/bin/rundetect.sh
	rm -f /var/.runxsetup
        unset PROGDIR
}

setup_firstboot() {
        unset PROGDIR
	/usr/local/bin/pc-firstgui
        rm /var/.pcbsd-firstgui
}

setup_xvesa() {
	echo "Using failsafe VESA 1024x768 mode..." >/dev/console
	mv /etc/X11/xorg.conf /etc/X11/xorg.conf.preVesa.backup
	cp /usr/local/share/pcbsd/xorg-gui/cardDetect/XF86Config.compat /etc/X11/xorg.conf
}

# Check if we are going to re-run the display setup wizard
y=`kenv runwiz 2>/dev/null`
if [ $? -eq 0 ]; then
   if [ "$y" = "YES" ] ; then
     touch /var/.runxsetup
   fi
   kenv -u runwiz
fi

xvesa="NO"
v=`kenv xvesa 2>/dev/null`
if [ $? -eq 0 ]; then
   xvesa=$v
fi

name="gdm"
rcvar=gdm_enable
command="/usr/local/sbin/${name}"
pidfile="/var/run/${name}.pid"
procname="/usr/local/sbin/gdm-binary"
start_cmd="gdm_start"

gdm_start()
{
    if ! checkyesno gdm_enable ; then
	return 0
    fi
    echo "Starting ${name}."
   
    # Update the pixbuf cache, otherwise weirdness insues
    gdk-pixbuf-query-loaders --update-cache

    # make sure there is no pam configuration for gdm service in base system
    if ! checkyesno gdm_preserve_base_pam_conf && [ -f /etc/pam.d/gdm ]; then
	cp -p /etc/pam.d/gdm /etc/pam.d/gdm_disabled
    	rm -f /etc/pam.d/gdm
    fi

    ( iter=0
    while ! ps -axoargs | grep "^/usr/libexec/getty " | grep -qv grep >/dev/null 2>&1; do
	if [ ${iter} -eq 60 ]; then
	    break
	fi
	sleep 1
	iter=$(expr ${iter} + 1)
    done
    iter=0
    while ! /usr/local/bin/lshal >/dev/null 2>&1 ; do
	if [ ${iter} -eq 60 ]; then
	    break
	fi
	sleep 1
	iter=$(expr ${iter} + 1)
    done

    # If the user wants to switch to failsafe X
    if [ ${xvesa} = "YES" ]; then
	setup_xvesa
    fi

    # If the user wants to switch to run the xorg setup again
    if [ -e "/var/.runxsetup" -a "$xvesa" != "YES" ]; then
    	setup_xorg
    fi

    # Check if we need to do a first boot setup
    if [ -e "/var/.pcbsd-firstgui" ]; then
       setup_firstboot
    fi

    # Start GDM now
    LANG=${gdm_lang} ${command} ${gdm_flags} ) &
}

load_rc_config ${name}
run_rc_command "$1"
